import com.sun.xml.internal.ws.resources.UtilMessages;

import javax.jws.Oneway;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;

class MyTimeTask implements Comparable<MyTimeTask>{
    private Runnable runnable;
    private long time;

    public MyTimeTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }


    @Override
    public int compareTo(MyTimeTask o) {
        return (int)(this.time-o.time);
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }
}

class MyTimer{
    private PriorityQueue<MyTimeTask> queue=new PriorityQueue<>();
    private Object locker=new Object();

    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            queue.offer(new MyTimeTask(runnable,delay));
            locker.notify();
        }
    }

    public MyTimer(){
        Thread thread = new Thread(()->{
            while(true){
                try{
                    synchronized(locker){
                        while(queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimeTask task=queue.peek();
                        long curTime=System.currentTimeMillis();
                        if(curTime>=task.getTime()){
                            task.getRunnable().run();
                            queue.poll();
                        }else{
                            locker.wait(task.getTime()-curTime);
                        }
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
}

public class demo2 {
    public static void main(String [] args){
        MyTimer timer=new MyTimer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
        System.out.println("程序启动");
    }
}
